<?php

namespace app\common\service\OrderService;

use app\model\BbcModel\ChannelBusiness;
use app\model\BbcModel\Commission;
use app\model\BbcModel\ConfigChannel;
use app\model\BbcModel\Host;
use app\model\BbcModel\MasterIncome;
use app\model\BbcModel\Order;
use app\model\BbcModel\OrderExtra;
use app\model\BbcModel\OrderGoods;
use app\model\BbcModel\OrderReturn;
use app\model\BbcModel\OrderReturnLog;
use app\model\BbcModel\Store;
use app\model\BbcModel\StoreMember;
use app\model\BbcModel\BusinessMember;
use app\common\service\PayService\HnaPay\HnPayClient;
use app\model\BbcModel\VipOrder;
use app\Normal;
use think\facade\Log;
use think\helper\Str;


/**
 * 订单售后服务
 * @author linan
 */
class OrderReturnService
{

    /**
     * 售后状态枚举
     */
    public function getReturnStatus()
    {
        $status=Order::instance()->return_status;
        $list=[];
        foreach ($status as $k=>$v){
            $item['return_status']=$k;
            $item['name']=$v;
            $list[]=$item;
        }
        return Normal::returnCode(Normal::SUC,"请求成功",$list);
    }

    /**
     * 售后详情
     */
    public function returnDetail(array $param = [])
    {
        if (empty($param['sn'])) {
            return Normal::returnCode(Normal::FAIL,"缺少参数sn");
        }
        $info = OrderReturn::instance()->info(['sn' => $param['sn'], '_fields_' => 'id,sn,check_status,amount,reason,reason_info,mobile,amount,pic,cd,refuse_reason','_order_'=>'id desc']);
        if (empty($info)) {
            return Normal::returnCode(Normal::FAIL,"售后不存在");
        }
        $info['status_name'] = OrderReturn::instance()->status[$info['check_status']];
        $info['cd'] = date('Y-m-d H:i:s', $info['cd']);
        $info['pay_type'] = '微信支付';
        $order = Order::instance()->info(['sn' => $info['sn']]);
        $info['pay_sn'] = $order['pay_sn'];
        $info['pay_time'] = date('Y-m-d H:i:s', $order['pay_time']);
        $orderextra=OrderExtra::instance()->info(['order_id'=>$order['id']]);
        $info['receive_name']=$orderextra['receive_name'];
        $info['receive_mobile']=$orderextra['receive_mobile'];
        $info['buyer_name']=$orderextra['buyer_name'];
        $info['buyer_mobile']=$orderextra['buyer_mobile'];
        $info['province']=$orderextra['province'];
        $info['city']=$orderextra['city'];
        $info['area']=$orderextra['area'];
        $info['address']=$orderextra['address'];
        $info['goods'] = $this->getGoodsList(['order_id' => $order['id']]);
        if (!empty($info['pic'])) {
            $info['pic'] = explode(',', $info['pic']);
        }
        return Normal::returnCode(Normal::SUC,"请求成功",$info);
    }

    /**
     * Q店订单商品列表
     */
    public function getGoodsList(array $param = [])
    {
        if (empty($param['order_id'])) {
            return [];
        }
        $fields = 'o.price,o.price_total,o.price_pay,o.num,o.goods_name,o.goods_id,o.price_total_reduce,o.price_tax,o.price_express,g.img,o.spec_num,g.unit_name';

        $list=OrderGoods::instance()
            ->alias('o')
            ->field($fields)
            ->join("goods g",'o.goods_id=g.id')
            ->where(['o.order_id'=>$param['order_id']])
            ->select()
            ->toArray();
        return $list;
    }

    /**
     * 订单售后审核
     * @param array $param
     * @return array
     */
    public function checkReturn(array $param)
    {
        if(empty($param['sn'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数sn");
        }
        if(empty($param['op'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数op");
        }
        if(empty($param['check_user_name'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数check_user_name");
        }
        $info=Order::instance()->info(['sn'=>$param['sn']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"订单不存在");
        }
        $extraInfo=OrderExtra::instance()->info(['order_id'=>$info['id']]);
        if($extraInfo['is_return']==0){
            return Normal::returnCode(Normal::FAIL,"订单未售后");
        }
        if($extraInfo['return_status']>1){
            return Normal::returnCode(Normal::FAIL,"订单已售后");
        }
        $return=OrderReturn::instance()->info(['sn'=>$param['sn'],'_order_'=>'id desc']);
        $log=[
            'sn'=>$param['sn'],
            'cd'=>time()
        ];
        if($param['op']==1){
            if($extraInfo['is_commission']==1){
                return Normal::returnCode(Normal::FAIL,"订单已分佣，无法售后");
            }
            try {
                OrderReturn::instance()->startTrans();
                $syncData['after_sale_status'] = 1;
                $syncData['order_sn'] = $info['sn'];
                $syncData['cid'] = $info['cid'];
                $syncData['exceptReason'] = $return['reason'];
                $edit['check_status']=1;
                $edit['check_user_name']=$param['check_user_name'];
                $edit['check_time']=time();
                if ($info['push_success'] == 1 && $info['type'] == 0 && $return['notice_cloud']==0 ) {
                    $OrderCloudService=new OrderCloudService();
                    if($info['push_pay_success']==1){
                        $res = $OrderCloudService->sendToStoB($syncData, 'OrderAfterSale');
                    }else{
                        $orderData = [
                            'orderSn' => $info['sn'],
                            'exceptReason' => '售后取消',
                            'cid' => $info['cid']
                        ];
                        $res = $OrderCloudService->sendToStoB($orderData, 'OrderCancel');
                    }
                    $msgArray=[
                        '当前订单不存在或已售后',
                        '提交售后状态失败',
                        '处理完成；【提交售后状态失败】',
                        '处理完成；【当前订单售后状态变更失败，请检查是否已经售后售后通过!】',
                        '【当前订单售后状态变更失败，请检查是否已经售后售后通过!】'
                    ];
                    if ($res['code']==0 && !in_array($res['msg'],$msgArray)) {
                        return [
                            'code' => Normal::FAIL,
                            'msg' => $res['msg'],
                        ];
                    }else{
                        $edit['notice_cloud']=1;
                    }
                }
                OrderReturn::instance()->edit(['id'=>$return['id']],$edit);
                Order::instance()->edit(['id'=>$info['id']],['pay_status'=>0,'status'=>0]);
                //修改服务商，渠道商，分销商的冻结金额
                $service=MasterIncome::instance()->info(['id'=>1]);
                MasterIncome::instance()->edit(['id'=>$service['id']],['frozen_income'=>$service['frozen_income']-$info['master_money']]);
                $business=ChannelBusiness::instance()->info(['id'=>$info['cb_id']]);
                $businessEdit=[
                    'frozen_income'=>$business['frozen_income']-$info['shop_money'],
                    'all_sell'=>$business['all_sell']-$info['price_order'],
                    'md'=>time()
                ];
                ChannelBusiness::instance()->edit(['id'=>$business['id']],$businessEdit);
                if($info['mn_sid']>0 && $info['shop_money']>0){
                    $store=Store::instance()->info(['id'=>$info['mn_sid']]);
                    $storeEdit=[
                        'frozen_income'=>$store['frozen_income']-$info['store_money'],
                        'all_sell'=>$store['all_sell']-$info['price_order'],
                        'md'=>time()
                    ];
                    Store::instance()->edit(['id'=>$store['id']],$storeEdit);
                }
                if($info['mnid']==4){
                    $member=StoreMember::instance()->info(['mid'=>$info['buy_mid'],'mn_sid'=>$info['mn_sid']]);
                    StoreMember::instance()->edit(['id'=>$member['id']],['consume'=>$member['consume']-$info['price_order']]);
                }else{
                    $member=BusinessMember::instance()->info(['mid'=>$info['mid'],'cb_id'=>$info['cb_id']]);
                    BusinessMember::instance()->edit(['id'=>$member['id']],['consume'=>$member['consume']-$info['price_order']]);
                }
                OrderExtra::instance()->edit(['id'=>$extraInfo['id']],['return_status'=>2]);
                Commission::instance()->edit(['sn'=>$info['sn']],['df'=>1]);
                $log['content']=$param['check_user_name'].'操作售后审核，审核通过';
                OrderReturnLog::instance()->add($log);
                OrderReturn::instance()->commit();
                return Normal::returnCode(Normal::SUC,"操作成功");
            }catch (\Exception $e){
                OrderReturn::instance()->rollback();
                $msg = $e->getMessage();
                return Normal::returnCode(Normal::FAIL,$msg);
            }
        }else{
            if(empty($param['refuse_reason'])){
                return Normal::returnCode(Normal::FAIL,"请输入拒绝原因");
            }
            OrderExtra::instance()->edit(['id'=>$extraInfo['id']],['return_status'=>0,'is_return'=>0]);
            OrderReturn::instance()->edit(['id'=>$return['id']],['check_time'=>time(),'check_status'=>2,'refuse_reason'=>$param['refuse_reason'],'check_user_name'=>$param['check_user_name']]);
            $log['content']=$param['check_user_name'].'操作售后审核，审核未通过';
            OrderReturnLog::instance()->add($log);
            return Normal::returnCode(Normal::SUC,"操作成功");
        }
    }

    /**
     * 订单售后退款
     * @param array $param
     * @return array
     */
    public function refundMoney(array $param)
    {
        if(empty($param['sn'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数sn");
        }
        if(empty($param['return_user_name'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数return_user_name");
        }
        if(empty($param['amount']) || $param['amount']<=0){
            return Normal::returnCode(Normal::FAIL,"退款金额要大于0");
        }
        $info=Order::instance()->info(['sn'=>$param['sn']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"订单不存在");
        }
        if($info['price_order']<$param['amount']){
            return Normal::returnCode(Normal::FAIL,"退款金额超过了订单金额");
        }
        $extraInfo=OrderExtra::instance()->info(['order_id'=>$info['id']]);
        if($extraInfo['is_return']==0){
            return Normal::returnCode(Normal::FAIL,"订单未售后");
        }
        if($extraInfo['return_status']==1){
            return Normal::returnCode(Normal::FAIL,"售后待审核");
        }
        if($extraInfo['return_status']==3){
            return Normal::returnCode(Normal::FAIL,"售后已退款");
        }
        $return=OrderReturn::instance()->info(['sn'=>$param['sn'],'_order_'=>'id desc']);
        try {
            OrderReturn::instance()->startTrans();
            $amount=$param['amount'];
            $out_refund_no = $return['sale_sn'];
            $host = Host::instance()->info(['tob'=>'notify','status'=>1]);
            $noticeUrl=$host['host'].'/master/HnpayReceive/returnOrder';
            $config= ConfigChannel::instance()->info(['cid'=>$info['cid'],'code'=>'hnapay_pay']);
            $payconfig=json_decode($config['value'],true);
            $order_data = [
                'merOrderId' => (string)$out_refund_no,
                'oldMerOrderId' =>(string)$info['pay_sn'],
                'amount' => (int)(round($amount * 100,2)),
                'currency' => 'CNY',
                'noticeUrl' => $noticeUrl,
            ];
            \think\facade\Log::write(json_encode($order_data,JSON_UNESCAPED_UNICODE),'hnapay_return_data');
            $result= HnPayClient::instance($payconfig)->returnOrder($order_data);
            \think\facade\Log::write(json_encode($result,JSON_UNESCAPED_UNICODE),'hnapay_return');
            if(($result['content']['responseCode'] !='0000' && $result['content']['responseCode'] !='0001') ||  $result['content']['status']==2){
                OrderReturn::instance()->rollback();
                return Normal::returnCode(Normal::FAIL,$result['content']['responseDesc']);
            }
            OrderExtra::instance()->edit(['id'=>$extraInfo['id']],['return_status'=>3]);
            OrderReturn::instance()->edit(['id'=>$return['id']],['return_money'=>1,'return_user_name'=>$param['return_user_name'],'return_time'=>time()]);
            $log=[
                'sn'=>$param['sn'],
                'content'=>$param['return_user_name'].'操作退款，退款金额:'.$amount,
                'cd'=>time()
            ];
            OrderReturnLog::instance()->add($log);
            OrderReturn::instance()->commit();
            return Normal::returnCode(Normal::SUC,"退款成功");
        }catch (\Exception $e){
            OrderReturn::instance()->rollback();
            $msg = $e->getMessage();
            return Normal::returnCode(Normal::FAIL,$msg);
        }
    }

    /**
     * 订单售后日志
     * @param array $param
     * @return array
     */
    public function returnLog(array $param)
    {
        if(empty($param['sn'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数sn");
        }
        $list=OrderReturnLog::instance()->lists(['sn'=>$param['sn']]);
        foreach ($list as $k=>$v){
            $list[$k]['cd']=date('Y-m-d H:i:s',$v['cd']);
        }
        return Normal::returnCode(Normal::SUC,"请求成功",$list);
    }

    /**
     * 售后回调
     */
    public function returnOrder(array $param)
    {
        if($param['content']['responseCode']!='0000' || $param['content']['status']==2){
            Log::write($param,'hnapay_return_notify_fail');
        }else{
            Log::write($param,'hnapay_return_notify_success');
        }
    }

    /**
     * 测试环境退款
     */
    public function returnMoney($param)
    {
        $host = Host::instance()->info(['tob'=>'notify','status'=>1]);
        $noticeUrl=$host['host'].'/master/HnpayReceive/returnOrder';
        $order=Order::instance()->lists(['pay_sn'=>$param['pay_sn']]);
        if(empty($order)){
            return Normal::returnCode(Normal::FAIL,"没找到订单");
        }
        $no=Str::random(6).time();
        $order_data = [
            'merOrderId' => (string)$no,
            'oldMerOrderId' =>$param['pay_sn'],
            'amount' => (int)round(array_sum(array_column($order,'price_order')) * 100),
            'currency' => 'CNY',
            'noticeUrl' => $noticeUrl,
        ];
        $config= ConfigChannel::instance()->info(['cid'=>$order[0]['cid'],'code'=>'hnapay_pay']);
        $payconfig=json_decode($config['value'],true);
        $result= HnPayClient::instance($payconfig)->returnOrder($order_data);
        return Normal::returnCode(Normal::SUC,"操作成功",$result);
    }


    /**
     * 测试环境会员
     */
    public function returnVipMoney($param)
    {
        $host = Host::instance()->info(['tob'=>'notify','status'=>1]);
        $noticeUrl=$host['host'].'/master/HnpayReceive/returnOrder';
        $order=VipOrder::instance()->info(['sn'=>$param['pay_sn']]);
        if(empty($order)){
            return Normal::returnCode(Normal::FAIL,"没找到订单");
        }
        $no=Str::random(6).time();
        $order_data = [
            'merOrderId' => (string)$no,
            'oldMerOrderId' =>$param['pay_sn'],
            'amount' => (int)round($order['amount'] * 100),
            'currency' => 'CNY',
            'noticeUrl' => $noticeUrl,
        ];
        $config= ConfigChannel::instance()->info(['cid'=>$order['cid'],'code'=>'hnapay_pay']);
        $payconfig=json_decode($config['value'],true);
        $result= HnPayClient::instance($payconfig)->returnOrder($order_data);
        return Normal::returnCode(Normal::SUC,"操作成功",$result);
    }


}

